package whf.framework.tools.generator.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import whf.framework.tools.generator.cfg.Config;

/**
 * 获取Oracle表的数据
 * @author wanghaifeng
 * @create Nov 2, 2006 10:41:29 AM
 * 
 */
public class OracleTableGetter extends AbstractTableGetter {

	private static Log log = LogFactory.getLog(OracleTableGetter.class);

	/**
	 * @param config
	 */
	public OracleTableGetter(Config config) {
		super(config);
	}
	
	/* (non-Javadoc)
	 * @see whf.framework.tools.generator.db.AbstractTableGetter#getTables()
	 */
	public List<Table> getTables() throws Exception {
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isEmpty(super.config.getTables()) || StringUtils.equalsIgnoreCase("all", super.config.getTables())) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			try{
				con = super.getConnection();
				pstmt = con.prepareStatement("select table_name from user_all_tables");
				rs = pstmt.executeQuery();
				while(rs.next()){
					sb.append(rs.getString(1)).append(",");
				}
				config.setTables(sb.toString());
			}catch(Exception e){
				log.error(this, e);
			}finally{
				super.close(rs);
				super.close(pstmt);
				super.close(con);
			}
		}
		return this.getTables(config.getTables());
	}
	
	/* (non-Javadoc)
	 * @see whf.framework.tools.generator.db.AbstractTableGetter#getTables(java.lang.String)
	 */
	public List<Table> getTables(String tableNames) throws Exception {
		log.info("正准备输出表:"+tableNames);
		String[] tables = StringUtils.split(tableNames, ",");
		List<Table> list = new ArrayList<Table>();
		for (int i = 0; tables != null && i < tables.length; i++) {
			if(StringUtils.isEmpty(tables[i])) continue;
			list.add(new OracleTable(super.getConnectionManager(), super.config.getSchema(), tables[i].trim(),
					super.config.getTablePrefix(), null));
		}
		return list;
	}
	
	public static void main(String[] args) throws Exception{
		Config config = new Config();
		config.setDriver("oracle.jdbc.driver.OracleDriver");
		config.setUrl("jdbc:oracle:thin:@192.168.20.8:1523:ora92");
		config.setUsername("wlrk_new");
		config.setPassword("a");
		OracleTableGetter getter = new OracleTableGetter(config);
		log.debug(getter.getTables());
	}
}
